package com.smile.commons.tree;

import java.util.*;
import java.util.function.BiConsumer;
import java.util.function.Function;

public class TreeConverter {

    /**
     * 树形结构类型转换方法
     */
    public static <S, T> List<T> convertTreeStructure(
            List<S> sourceTree,
            Function<S, T> nodeConverter,
            Function<S, List<S>> sourceChildrenGetter,
            BiConsumer<T, List<T>> targetChildrenSetter) {

        List<T> result = new ArrayList<>();
        for (S sourceNode : sourceTree) {
            result.add(convertNodeRecursive(sourceNode, nodeConverter, sourceChildrenGetter, targetChildrenSetter));
        }
        return result;
    }

    private static <S, T> T convertNodeRecursive(
            S sourceNode,
            Function<S, T> nodeConverter,
            Function<S, List<S>> sourceChildrenGetter,
            BiConsumer<T, List<T>> targetChildrenSetter) {

        // 转换当前节点
        T targetNode = nodeConverter.apply(sourceNode);

        // 递归转换子节点
        List<S> sourceChildren = sourceChildrenGetter.apply(sourceNode);
        if (sourceChildren != null && !sourceChildren.isEmpty()) {
            List<T> targetChildren = new ArrayList<>();
            for (S child : sourceChildren) {
                targetChildren.add(convertNodeRecursive(
                        child, nodeConverter,
                        sourceChildrenGetter, targetChildrenSetter
                ));
            }
            targetChildrenSetter.accept(targetNode, targetChildren);
        }

        return targetNode;
    }
}